package com.ruoyi.walmart.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.WalmartConstant;
import com.ruoyi.common.exception.ServiceException;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.walmart.domain.Inventory.Inventory;
import com.ruoyi.walmart.domain.InventoryLog.InventoryLogSearch;
import com.ruoyi.walmart.domain.ProductParameters;
import com.ruoyi.walmart.domain.auth.ShopAuth;
import com.ruoyi.walmart.domain.order.Meta;
import com.ruoyi.walmart.domain.shipments.ShipmentCondition;
import com.ruoyi.walmart.http.WalmartRequest;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.binary.Base64;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Log4j2
public class walmartUtil {

    /**
     * 获取访问Us站点API的请求头
     *
     * @param requestUrl 请求url
     * @param method     请求方式
     * @param paramMap   请求参数
     * @return 返回请求头map
     */
    public static Map<String, String> getHeaders(String requestUrl,
                                                 Method method,
                                                 Map<String, ?> paramMap,ShopAuth shopAuth) {
        String authorization = getAuthorization(shopAuth.getClientId(), shopAuth.getClientSecret());
        Map<String, String> headers = new HashMap<>();
        headers.put("WM_SVC.NAME", WalmartConstant.ACCOUNT_NAME);
        headers.put("WM_QOS.CORRELATION_ID", IdUtil.randomUUID());
        headers.put("Authorization", authorization);
        headers.put("WM_SEC.ACCESS_TOKEN", getAccessToken(authorization));
        headers.put("Accept","application/json");
        if(Method.POST == method){
            headers.put("Content-Type", "application/json");
        }
        return headers;
    }
    /**
     * 对密钥进行编码
     *
     * @param appKey    app key
     * @param appSecret app秘钥
     * @return bese64编码字符串
     */
    public static String getAuthorization(String appKey, String appSecret) {
        String str = appKey + ":" + appSecret;
        return "Basic " + Base64.encodeBase64String(str.getBytes());
    }

    /**
     * 获取美国店铺的token
     *
     * @return
     */
    public static String getAccessToken(String authorization) {

        String accessToken = "";
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", authorization);
        headers.put("WM_SVC.NAME", WalmartConstant.ACCOUNT_NAME);
        headers.put("WM_QOS.CORRELATION_ID", IdUtil.randomUUID());
        try {
            HttpResponse response = HttpRequest.post("https://marketplace.walmartapis.com" + "/v3/token")
                    .addHeaders(headers)
                    .body("grant_type=client_credentials", "application/x-www-form-urlencoded")
                    .execute();

            JSONObject jsonObject = JSONUtil.parseObj(response.body());
            accessToken = jsonObject.getStr("access_token");
            if (accessToken == null) {
                log.error("walmart获取token请求失败body:{}",response.body());
                throw new ServiceException("获取沃尔玛接口调用凭证失败", 500);
            }
        } catch (Exception e) {
            log.error("【获取美国站点token值异常】，{}", e.getMessage());
            throw new ServiceException("【获取美国站点token值异常】，{}", 500);
        }
        return accessToken;
    }

    public static com.alibaba.fastjson2.JSONObject listItemsUs(ProductParameters productParameters, ShopAuth shopAuth){
        String nextCursor = Optional.ofNullable(productParameters.getNextCursor()).orElse("*");
        //String lifecycleStatus = Optional.ofNullable(productParameters.getLifecycleStatus()).orElse("ACTIVE");
        //String publishedStatus = Optional.ofNullable(productParameters.getPublishedStatus()).orElse("PUBLISHED");
        //String condition = Optional.ofNullable(productParameters.getCondition()).orElse("New");
        String limit = Optional.ofNullable(productParameters.getLimit()).orElse("50");
        //String urLUS = WalmartConstant.BASE_URL+WalmartConstant.GET_PRODUCTS_US_URL+"?nextCursor="+nextCursor+"&limit="+limit+"&lifecycleStatus="+lifecycleStatus+"&publishedStatus="+publishedStatus+"&condition="+condition;
        String urLUS = WalmartConstant.BASE_URL+WalmartConstant.GET_PRODUCTS_US_URL+"?nextCursor="+nextCursor+"&limit="+limit;
        String request = WalmartRequest.request(urLUS, Method.GET, null,shopAuth);
        if(StringUtils.isEmpty(request)){
            return null;
        }
        return JSON.parseObject(request);
    }
    public static com.alibaba.fastjson2.JSONObject listOrdersUs(Meta meta, ShopAuth shopAuth) {
        String nextCursor = Optional.ofNullable(meta.getNextCursor()).orElse("*");
        String shipNodeType = Optional.ofNullable(meta.getShipNodeType()).orElse("WFSFulfilled");
        String replacementInfo = Optional.ofNullable(meta.getReplacementInfo()).orElse("true");
        String limit = Optional.ofNullable(meta.getLimit()).orElse("200");

        // **创建时间参数**
        String createdStartDate;
        String createdEndDate;

        if (meta.getCreatedStartDate() == null || meta.getCreatedStartDate().isEmpty()) {
            DateTime offset = DateUtil.offsetDay(new Date(), -180);
            createdStartDate = DateUtil.format(offset, "yyyy-MM-dd'T'HH:mm:ss'Z'");
        } else {
            createdStartDate = meta.getCreatedStartDate();
        }

        // **确保 createdEndDate 限制查询范围**
        createdEndDate = DateUtil.format(new Date(), "yyyy-MM-dd'T'HH:mm:ss'Z'");

        // **构造 Walmart API URL**
        String urlUS;
        if (nextCursor.equals("*")) {
            urlUS = WalmartConstant.BASE_URL + WalmartConstant.GET_ALL_ORDER_US_URL +
                    "?nextCursor=" + nextCursor +
                    "&shipNodeType=" + shipNodeType +
                    "&replacementInfo=" + replacementInfo +
                    "&createdStartDate=" + createdStartDate +
                    "&createdEndDate=" + createdEndDate + // **新增 createdEndDate**
                    "&limit=" + limit;
        } else {
            urlUS = WalmartConstant.BASE_URL + WalmartConstant.GET_ALL_ORDER_US_URL +
                    nextCursor;
        }

        System.out.println("urlUS:::" + urlUS);

        // **发送 Walmart API 请求**
        String request = WalmartRequest.request(urlUS, Method.GET, null, shopAuth);
        if (StringUtils.isEmpty(request)) {
            return null;
        }

        return JSON.parseObject(request);
    }

    public static com.alibaba.fastjson2.JSONObject listInventoryUs(Inventory inventory,ShopAuth shopAuth){
        Integer limit = Optional.ofNullable(inventory.getLimit()).orElse(300);
        Integer offset = Optional.ofNullable(inventory.getOffset()).orElse(0);
        String urLUS = WalmartConstant.BASE_URL+WalmartConstant.GET_FULFILLMENT_US_URL+"?limit="+limit+"&offset="+offset;
        String request = WalmartRequest.request(urLUS,Method.GET,null,shopAuth);
        if(StringUtils.isEmpty(request)){
            return null;
        }
        return JSON.parseObject(request);
    }

    public static com.alibaba.fastjson2.JSONObject listShipmentUs(ShipmentCondition shipmentCondition, ShopAuth shopAuth){
        Integer limit = Optional.ofNullable(shipmentCondition.getLimit()).orElse(300);
        Integer offset = Optional.ofNullable(shipmentCondition.getOffset()).orElse(0);
        String shipmentId = Optional.ofNullable(shipmentCondition.getShipmentId()).orElse("");
        LocalDateTime fromCreateDate = Optional.ofNullable(shipmentCondition.getFromCreateDate()).orElse(null);
        String urlUs = WalmartConstant.BASE_URL+WalmartConstant.GET_SHIPMENTS_US_URL+"?limit="+limit+"&offset="+offset;
        // 如果 shipmentId 不为空，则将其加入到 URL 中
        if (!shipmentId.isEmpty()) {
            urlUs += "&shipmentId=" + shipmentId;
        }
        if(fromCreateDate != null){
            urlUs += "&fromCreateDate=" + fromCreateDate;
        }
        String request = WalmartRequest.request(urlUs,Method.GET,null,shopAuth);
        if(StringUtils.isEmpty(request)){
            return null;
        }
        return JSON.parseObject(request);
    }
    //获取库存日志
    public static com.alibaba.fastjson2.JSONObject listInventoryLogUS(InventoryLogSearch inventoryLog, ShopAuth shopAuth) {
        Integer limit = Optional.ofNullable(inventoryLog.getLimit()).orElse(1000);
        Integer offset = Optional.ofNullable(inventoryLog.getOffset()).orElse(0);
        String gtin  = inventoryLog.getGtin();
        Map<String, Object> paramMap = new HashMap<>();
        String shipmentId = "";
        String transactionType = Optional.ofNullable(inventoryLog.getTransactionType()).orElse("");
        String transactionLocation = Optional.ofNullable(inventoryLog.getTransactionLocation()).orElse("");
        String startDate = "";
        if(inventoryLog.getStartDate() != null){
            startDate = new SimpleDateFormat("yyyy-MM-dd").format(inventoryLog.getStartDate());
            paramMap.put("startDate",startDate);
        }
        String endDate = "";
        String sort_by = "transactionTime";
        String sort_order = "ASC";

        paramMap.put("sort_order",sort_order);
        paramMap.put("sort_by",sort_by);

        String urlUs = WalmartConstant.BASE_URL+WalmartConstant.GET_FULFILLMENT_lOG_URL+"?gtin="+gtin+"&limit="+limit+"&offset="+offset;
        if(transactionType != null){
            urlUs += "&transactionType=" + transactionType;
        }
        if(transactionLocation != null){
            urlUs += "&transactionLocation=" + transactionLocation;
        }
        String request = WalmartRequest.request(urlUs,Method.GET,paramMap,shopAuth);
        if(StringUtils.isEmpty(request)){
            return null;
        }
        return JSON.parseObject(request);
    }

    // 将当前时间转换为美西时间，并减去指定天数
    public static ZonedDateTime offsetDayAndConvertToPacific(Date orderDate, int daysToOffset) {
        // 将 Date 转换为 ZonedDateTime（默认使用系统默认时区）
        ZonedDateTime pacificDateTime = orderDate.toInstant()
                .atZone(ZoneId.systemDefault()); // 使用系统默认时区
        // 判断当前时间是否处于夏令时（PDT），若是则加 7 小时，否则加 8 小时（PST）
        int hoursToAdd = pacificDateTime.getZone().getRules().isDaylightSavings(pacificDateTime.toInstant()) ? 7 : 8;

        // 动态加上 7 或 8 小时
        pacificDateTime = pacificDateTime.minusHours(hoursToAdd);
        // 减去180天
        pacificDateTime = pacificDateTime.minusDays(daysToOffset);

        return pacificDateTime;
    }
    // 格式化时间为符合沃尔玛 API 要求的格式
    public static String DateFormat(ZonedDateTime dateTime, String pattern) {
        DateTimeFormatter isoFormatter = DateTimeFormatter.ofPattern(pattern);
        return isoFormatter.format(dateTime);
    }

    public static Date formattedTime(Date originalTime, String formattedDate) {
        ZonedDateTime pacificDateTime = originalTime.toInstant()
                .atZone(ZoneId.systemDefault()); // 使用系统默认时区
        // 判断当前时间是否处于夏令时（PDT），若是则加 7 小时，否则加 8 小时（PST）
        int hoursToAdd = pacificDateTime.getZone().getRules().isDaylightSavings(pacificDateTime.toInstant()) ? 7 : 8;

        // 将 Date 转换为 Instant
        Instant instant = originalTime.toInstant();
        // 将 Instant 转换为 OffsetDateTime（假设为 UTC 时区）
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.UTC);
        offsetDateTime = offsetDateTime.plusHours(hoursToAdd);
        // 格式化为没有时区的字符串（格式：yyyy-MM-dd HH:mm:ss）
        String formattedTimeString = offsetDateTime.format(DateTimeFormatter.ofPattern(formattedDate));

        // 使用 SimpleDateFormat 将格式化后的字符串转换为 Date 对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date formattedDateObj = null;
        try {
            formattedDateObj = dateFormat.parse(formattedTimeString);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return formattedDateObj;
    }
}
